/**
 * jq.web.slidable - a slidable for html5 mobile apps
 * Copyright 2012 - HundSun 
 */
(function($){

	$.fn["slidable"] = function(conf){
		//console.log("damn it");
		conf = $.extend({}, $.slidable.conf, conf); 
		this.each(function() {			
			new Slidable($(this), conf);
		});
		return this; 
	};

	$.slidable = {
		conf: {	
			activeClass: 'active',
			circular: false,
			clonedClass: 'cloned',
			disabledClass: 'disabled',
			easing: 'swing',
			initialIndex: 0,
			item: null,
			items: '.items',
			keyboard: true,
			mousewheel: false,
			next: '.next',   
			prev: '.prev', 
			speed: 400,
			vertical: false,
			touch: true,
			wheelSpeed: 0,
			checkable:false,
			multiCheck:false
		}
	};
	
    function Slidable(root, conf) {
    	$.extend(this, {
    		selected:conf['selected'],
    		checked:conf['checked'],
    		checkable:conf['checkable'],
	    	multiCheck:conf['multiCheck'],
    		activeDiv:"",
			previousDiv:"",
		
			css3animate: function(el, opts) {
	            el = $(el);
	            if (!el.__proto__["css3Animate"])
	                throw "css3Animate plugin is required";
	            return el.css3Animate(opts);
	        },
			
			slide: function (newDiv, back) {
				var oldDiv = this.activeDiv;
	            oldDiv.style.display = "none";
	            newDiv.style.display = "block";
	            var that = this;
	            
	            if (back) {
	                this.css3animate(oldDiv, {
	                    x: "100%",
	                    time: "200ms",
	                    callback: function() {
	                        that.previousDiv = oldDiv;
	                        that.css3animate(oldDiv, {
	                            x: 0,
	                            time: "0ms"
	                        });
	                    }
	                });
	                this.css3animate(newDiv, {
	                    x: "-100%",
	                    time: "0ms",
	                    callback: function() {
							that.activeDiv = newDiv;
	                        that.css3animate(newDiv, {
	                            x: "0%",
	                            time: "200ms"
	                        });
	                    }
	                });
	            } else {
	                this.css3animate(oldDiv, {
	                    x: "-100%",
	                    time: "200ms",
	                    callback: function() {
	                    	that.previousDiv = oldDiv;
	                    }
	                });
	                this.css3animate(newDiv, {
	                    x: "100%",
	                    time: "0ms",
	                    callback: function() {
							that.activeDiv = newDiv;
	                        that.css3animate(newDiv, {
	                            x: "0%",
	                            time: "200ms"
	                        });
	                    }
	                });
	            }
	        },
	        
	        build: function (root,id,data,text,parentid){
				var slidableDiv = $("<div id='"+id+"' />");
				var header =$("<h5>"+text+"</h5>");
				if(parentid){
					var returnAnchor = $("<a href='#"+parentid+"' class='upward' data-ignore='true'></a>");
					header.append(returnAnchor);
				}
				var that = this;
				slidableDiv.append(header);
				
				var ul = $("<ul class='navul'></ul>");
				$.each(data,function(index,value){
		            if(value) {
		                var li = $("<li></li>");
		                if( typeof value == 'string') {
		                    li.append("<a href='#' class='empty' data-ignore='true'>" + value + "</a>");
		                } else {
		                    if(value['text'] && value['id']) {
		                        var achor = $("<a href='#" + value['id'] + "' data-ignore='true'>" + value['text'] + "</a>");
		                        li.append(achor);
		                        if(value['leaf'] == 'true' || !value['children']) {
		                            achor.addClass('empty');
		                        }
		                        if(value['selected']) {
		                            var selectedFunc = value['selected'];
		
		                            var eventHandler = function(e) {
		                                selectedFunc.apply(achor, [value, e]);
		                            }
		                            achor.bind('click', eventHandler);
		                            //achor.bind('click',value,value['selected']);
		                            //achor.get(0).addEventListener('click', eventHander, false);
		                        }
		                        //li.append(achor);
		                    }
		                    if(!value['leaf']) {
		                        that.build(root, value['id'], value['children'], value['text'], id);
		                    }
		                    if(value['children']) {
		                        that.build(root, value['id'], value['children'], value['text'], id);
		                    }
		                }
		                ul.append(li);
		            }
		
				});
				slidableDiv.append(ul);
				slidableDiv.css("display","none");
				root.append(slidableDiv);
				return slidableDiv;
			},
			
			create: function(root,id,ajaxObj,params,text,parentid){
			    
				if(root.find("[id='" + id + "']").length > 0){
					//this.slide($("#"+id).get(0), false);
					this.slide(root.find("[id='" + id + "']").get(0), false);
					return;
				}
				var that = this;
				var url =  ajaxObj['url'];
				$.ajax({
			         url: url,  
			         type: "post",  
			         dataType: "json",  
			         data:params,
			         success: function(data){
		                var slidableDiv = $("<div id='" + id + "' />");
		                var header = $("<h5>" + text + "</h5>");
		                var returnAnchor = $("<a href='#" + parentid + "' class='upward' data-ignore='true'></a>");
		                if(parentid) {
		                    header.append(returnAnchor);
		                }
		
		                slidableDiv.append(header);
		
		                var ul = $("<ul class='navul'></ul>");
		                $.each(data, function(index, value) {
		                    var li = $("<li></li>");
		                    if(typeof value == 'string') {
		                        var achor = $("<a href='#' class='empty' data-ignore='true'>"+value+"</a>");
		                        li.append(achor);
		                        if(that.selected && typeof that.selected == 'function'){
									var eventHandler = function(e){
										that.selected.apply(achor, [value,e]);
									}
									achor.bind('click',eventHandler);
								}
		                    } else {
		                        if(value['text'] && value['id']) {
		                            var achor = $("<a href='#" + value['id'] + "' data-ignore='true'>" + value['text'] + "</a>");
		                            if(that.checkable){
			                        	if(that.multiCheck){
				                        	var checkBox = $('<input name="'+value['id']+'" type="checkbox" value="" ></input>');
					                        li.append(checkBox);
			                        	}else{
			                        		var checkBox = $('<input name="'+value['text']+'" type="radio" value="'+value['text']+'" ></input>');
					                        li.append(checkBox);
			                        	}
			                        	
			                            if(that.checked && typeof that.checked == 'function'){
											var eventHandler = function(e){
												that.checked.apply(achor, [value,e]);
											}
											checkBox.bind('click',eventHandler);
										}
			                        }
		                            if(value['leaf']) {
		                                achor.addClass('empty');
		                            }
		                            li.append(achor);
		                            var postData = {};
		                            var postDataFunc = ajaxObj['data'];
									if(postDataFunc && typeof postDataFunc == 'function'){
										postData = postDataFunc.apply(null, [value]);
									}
		                            if(!value['leaf']) {
			                            achor.bind('click', function(e) {
				                                that.create(root, value['id'], ajaxObj, postData, value['text'], id);
			                            });
			                        }
		                            
		                            if(that.selected && typeof that.selected == 'function'){
										var eventHandler = function(e){
											that.selected.apply(achor, [value,e]);
										}
										achor.bind('click',eventHandler);
									}
		                        }
		                    }
		                    ul.append(li);
		                });
		                slidableDiv.append(ul);
		                root.append(slidableDiv);
		                returnAnchor.bind('click', function(e) {
		                    //that.slide($("#"+parentid).get(0), true);
		                    that.slide(root.find("[id='" + parentid + "']").get(0),true);
		                });
		                
		                if(!that.activeDiv){
		                	slidableDiv.show();
		                	that.activeDiv = slidableDiv.get(0);
		                }else{
			                that.slide(slidableDiv.get(0), false);
		                }
		            }
		  
				});
		        //$.post(url, params, function(data) {}, "json");
		    },
				
		    dwr: function(root,dwrObj,params,text,parentid){
		    	var id = dwrObj['javaParams'][1];
				if(root.find("[id='" + id + "']").length > 0){
					this.slide(root.find("[id='" + id + "']").get(0), false);
					return;
				}
				var that = this;
				
			     DWREngine._execute(
				     dwrObj['url'],
				     dwrObj['javaClass'],
				     dwrObj['javaMethon'],
					 dwrObj['javaParams'][0],
					 dwrObj['javaParams'][1],
					 dwrObj['javaParams'][2],
					 dwrObj['javaParams'][3],
					  function(data){
						//debugger;
						var dataObjs = data[0].children;
					  	
					  	
		                var slidableDiv = $("<div id='" + id + "' />");
		                var header = $("<h5>" + text + "</h5>");
		                var returnAnchor = $("<a href='#" + parentid + "' class='upward' data-ignore='true'></a>");
		                if(parentid) {
		                    header.append(returnAnchor);
		                }
		
		                slidableDiv.append(header);
		
		                var ul = $("<ul class='navul'></ul>");
		                $.each(dataObjs, function(index, value) {
		                    var li = $("<li></li>");
		                    if(typeof value == 'string') {
		                        var achor = $("<a href='#' class='empty' data-ignore='true'>"+value+"</a>");
		                        li.append(achor);
		                        if(that.selected && typeof that.selected == 'function'){
									var eventHandler = function(e){
										that.selected.apply(achor, [value,e]);
									}
									achor.bind('click',eventHandler);
								}
		                    } else {
		                        if(value['title'] && value['id']) {
		                            var achor = $("<a href='#" + value['id'] + "' data-ignore='true'>" + value['title'] + "</a>");
		                            if(that.checkable){
			                        	if(that.multiCheck){
				                        	var checkBox = $('<input name="'+text+'" type="checkbox" value="'+value['id']+'" ></input>');
					                        li.append(checkBox);
			                        	}else{
			                        		var checkBox = $('<input name="'+text+'" type="radio" value="'+value['id']+'" class="jq-ui-forms" style="width:35px;"></input><label for="'+text+'" style="margin:5px" ></label>');
					                        li.append(checkBox);
			                        	}
			                        	
			                            if(that.checked && typeof that.checked == 'function'){
											var eventHandler = function(e){
												that.checked.apply(achor, [value,e]);
											}
											checkBox.bind('click',eventHandler);
										}
			                        }
		                            if(!value['isFolder']) {
		                                achor.addClass('empty');
		                            }
		                            li.append(achor);
		                            var postData = {};
		                            var postDataFunc = dwrObj['data'];
									if(postDataFunc && typeof postDataFunc == 'function'){
										postData = postDataFunc.apply(null, [value]);
									}
		                            if(value['isFolder']) {
			                            achor.bind('click', function(e) {
			                            		dwrObj['javaParams'][1] = value['id'];
				                                that.dwr(root, dwrObj, postData, value['title'], id);
			                            });
			                        }
		                            
		                            if(that.selected && typeof that.selected == 'function'){
										var eventHandler = function(e){
											that.selected.apply(achor, [value,e]);
										}
										achor.bind('click',eventHandler);
									}
		                        }
		                    }
		                    ul.append(li);
		                });
		                slidableDiv.append(ul);
		                root.append(slidableDiv);
		                returnAnchor.bind('click', function(e) {
		                	that.slide(root.find("[id='" + parentid + "']").get(0), true);
		                    //that.slide($("#"+parentid).get(0), true);
		                });
		                
		                if(!that.activeDiv){
		                	slidableDiv.show();
		                	that.activeDiv = slidableDiv.get(0);
		                }else{
			                that.slide(slidableDiv.get(0), false);
		                }
						
    
					  });
		        
		    }
		});
		
        if(conf['json_data']) {
        	var id = conf['id'];
	        var text = conf['text'];
            var json_data = conf['json_data'];
            if(json_data['data']) {
                var data = json_data['data'];

                var div = this.build(root, id, data, text);
                this.activeDiv = div.get(0);
                div.show();
				var that = this;
                root.find("a").bind('click', function() {
                    var href = $(this).attr('href');
                    if(href.indexOf("#") !== -1 && $(href).length > 0) {
                        var back = $(this).attr('class') == 'upward' ? true : false;
                        that.slide($(href).get(0), back);
                    }
                });
            }
            if(json_data['ajax']){
            	var ajax = json_data['ajax'];
        		this.create(root, id, ajax, json_data['params'], text);
            }
            if(json_data['dwr']){
            	var dwr = json_data['dwr'];
            	this.dwr(root, dwr, json_data['params'], text);
            }
        }

    };
			
})(jq);
